package com.xunwulian.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.xunwulian.api.iface.AppAPI;
import com.xunwulian.api.iface.UserAPI;
import com.xunwulian.base.entity.AppEntity;
import com.xunwulian.base.entity.Page;
import com.xunwulian.base.entity.User;
import com.xunwulian.base.util.PageData;
import com.xunwulian.base.util.UserUtil;
import com.xunwulian.web.util.AppUtil;
import com.xunwulian.web.util.Const;
import com.xunwulian.web.util.JurisdictionHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/app")
public class AppController extends BaseController {

    String menuUrl = "app/list.do"; // 菜单地址(权限用)

    String appId = System.getenv("appId");
    String registryAddress = System.getenv("registry");

    @Reference
    private AppAPI appAPI;
    @Reference
    private UserAPI userAPI;

//    private AppAPI appAPI = new Consumer<AppAPI>().getApi(AppAPI.class, ConstantBean.XWL_GROUP, appId, registryAddress);
//    private UserAPI userAPI = new Consumer<UserAPI>().getApi(UserAPI.class, ConstantBean.XWL_GROUP, appId, registryAddress);

    private Gson gson = new Gson();

    /**
     * 保存用户
     *
     * @param out
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/saveApp")
    public ModelAndView saveApp(PrintWriter out) throws Exception {

        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();


        // 从session获取用户信息
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        String userName = pd.getString("USERNAME");
        String name = pd.getString("NAME");
        String number = pd.getString("NUMBER");
        String phone = pd.getString("PHONE");
        String bz = pd.getString("BZ");
        String roleId = pd.getString("ROLE_ID");
        String email = pd.getString("EMAIL");
        String appId = pd.getString("APP_ID");

        User userEntity = new User();

        userEntity.setUSER_ID(this.get32UUID()); // ID
        userEntity.setRIGHTS("");
        userEntity.setLAST_LOGIN("");
        userEntity.setIP("");
        userEntity.setSTATUS("0");
        userEntity.setSkin("default");
        // 设置应用平台
        userEntity.setAppId(appId);

        userEntity.setCreator(user.getUSER_ID());

        userEntity.setUSERNAME(userName == null ? "" : userName);
        userEntity.setNAME(name == null ? "" : name);
        userEntity.setNumber(pd.getString("NUMBER") == null ? "" : number);
        userEntity.setPhone(phone == null ? "" : phone);
        userEntity.setBz(bz == null ? "" : bz);
        userEntity.setROLE_ID(roleId == null ? "" : roleId);
        userEntity.setEmail(email == null ? "" : email);

        logger.info("pd:" + gson.toJson(pd));

        String password = pd.getString("PASSWORD");

        userEntity.setPASSWORD(new SimpleHash("SHA-1", userName, password).toString());

        if (null == userAPI.getByName(userName)) {
            if (JurisdictionHelper.buttonJurisdiction(menuUrl, "add")) {
                userAPI.saveU(userEntity);
            }
            // 判断新增权限
            mv.addObject("msg", "success");
        } else {
            mv.addObject("msg", "failed");
        }
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 修改用户
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/editApp")
    public ModelAndView editApp() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();

        String password = pd.getString("PASSWORD");
        String userName = pd.getString("USERNAME");
        if (password != null && !"".equals(password)) {
            pd.put("PASSWORD", new SimpleHash("SHA-1", userName, password).toString());
        }
        if (JurisdictionHelper.buttonJurisdiction(menuUrl, "edit")) {

            User user = new User(pd.getString("USER_ID"),
                    pd.getString("USERNAME"),
                    pd.getString("PASSWORD"),
                    pd.getString("NAME"),
                    pd.getString("ROLE_ID"),
                    pd.getString("BZ"),
                    pd.getString("EMAIL"),
                    pd.getString("NUMBER"),
                    pd.getString("PHONE"));

            userAPI.editU(user);
        }

        mv.addObject("msg", "success");
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 去修改用户页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goEditApp")
    public ModelAndView goEditApp() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();

        // 从session获取用户信息
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        // 顶部修改个人资料
        String fx = pd.getString("fx");

        logger.info("去修改用户页面，" + fx);

        if ("head".equals(fx)) {
            mv.addObject("fx", "head");
        } else {
            mv.addObject("fx", "user");
        }

        String appId = pd.getString("APP_ID");
        AppEntity app = (AppEntity) appAPI.getApp(appId).getData();

        mv.setViewName("system/app/app_edit");
        mv.addObject("msg", "editApp");
        mv.addObject("app", app);
        mv.addObject("appList", appAPI.list(user.getROLE_ID(), user.getAppId()));

        return mv;
    }

    /**
     * 去新增用户页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goAddApp")
    public ModelAndView goAddApp() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();

        // 从session获取用户信息
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        pd.put("USERID", user.getUSER_ID());
        pd.put("ROLEID", user.getROLE_ID());
        pd.put("APPID", user.getAppId());

        logger.info("pd:" + gson.toJson(pd));

        mv.setViewName("system/app/app_edit");
        mv.addObject("msg", "saveApp");
        mv.addObject("pd", pd);
        mv.addObject("appList", appAPI.list(user.getROLE_ID(), user.getAppId()));

        return mv;
    }

    /**
     * 显示应用平台列表
     *\
     * @param page
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list")
    public ModelAndView list(Page page) throws Exception {
        ModelAndView mv = this.getModelAndView();

        // 从session获取用户信息
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        List appList = new ArrayList();
        if (UserUtil.isAdmin(user)) {
            appList = appAPI.listPageByAll(page);
        } else {
            appList.add(appAPI.getApp(user.getAppId()).getData());
        }

        logger.info("appList:", appList);

        mv.setViewName("system/app/app_list");

        mv.addObject("appList", appList);

        mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限

        return mv;
    }

    /**
     * 删除用户
     *
     * @param out
     */
    @RequestMapping(value = "/deleteU")
    public void deleteU(PrintWriter out) {
        PageData pd = new PageData();
        try {
            pd = this.getPageData();
            if (JurisdictionHelper.buttonJurisdiction(menuUrl, "del")) {
                String userId = pd.getString("USER_ID");
                userAPI.deleteU(userId);
            }
            out.write("success");
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }

    /**
     * 批量删除
     *
     * @return
     */
    @RequestMapping(value = "/deleteAllU")
    @ResponseBody
    public Object deleteAllU() {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            pd = this.getPageData();
            List<PageData> pdList = new ArrayList<PageData>();
            String USER_IDS = pd.getString("USER_IDS");

            if (null != USER_IDS && !"".equals(USER_IDS)) {
                List<String> idList = Lists.newArrayList(USER_IDS.split(","));
                if (JurisdictionHelper.buttonJurisdiction(menuUrl, "del")) {
                    userAPI.deleteAllU(idList);
                }
                pd.put("msg", "ok");
            } else {
                pd.put("msg", "no");
            }

            pdList.add(pd);
            map.put("list", pdList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return AppUtil.returnObject(pd, map);
    }

    /**
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format,
                true));
    }

    /**
     * @return
     */
    public Map<String, String> getHC() {
        Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }
}
